package main

import (
	myErr "cogpt/internal/cogpterror"
	"flag"
	"fmt"
	"time"
)

func main() {
	// parse flags
	flag.StringVar(&proxyAddress, "proxy", proxyAddress, "proxy address")
	flag.Parse()

	loginInfo, err := getLoginInfo()
	if err != nil {
		if err.Code() == myErr.ERR_REQUEST_TIMEOUT {
			fmt.Println("Request timeout. Please check your network connection and try again.")
			return
		} else if err.Code() == myErr.ERR_UNKNOWN_PROXY_TYPE {
			fmt.Println("Unknown proxy type. Please check your proxy address and try again.")
			return
		}
		panic(err)
	}

	fmt.Println(
		"Please open",
		loginInfo.Verification_uri,
		"in browser and enter",
		loginInfo.User_code,
		"to login.",
	)

	for {
		accessToken, err := pollAuth(loginInfo.Device_code)
		if err == nil {
			fmt.Println("Access token:")
			fmt.Println(accessToken)
			break
		}
		switch err.Code() {
		case myErr.ERR_AUTH_PENDING:
			time.Sleep(time.Duration(loginInfo.Interval) * time.Second)
			continue
		case myErr.ERR_EXPIRED_TOKEN:
			fmt.Println("Session expired. Please try again.")
			return
		case myErr.ERR_REQUEST_TIMEOUT:
			fmt.Println("Request timeout. Please check your network connection and try again.")
			return
		default:
			panic(err)
		}
	}

	fmt.Println()
	fmt.Print("Press 'Enter' to exit...")
	fmt.Scanln()
}
